//
//  UIBarButtonItem+CustomBadge.m
//  BBP
//
//  Created by 余礼钵 on 16/3/23.
//  Copyright © 2016年 TangYunfei. All rights reserved.
//

#import "UIBarButtonItem+CustomBadge.h"
#import <Masonry.h>


#define CUSTOM_BADGE_TAG 2017121001
#define OFFSET 0.6f

@implementation UIBarButtonItem (CustomBadge)

- (void)setMyAppCustomBadgeValue:(NSString *) value
{
    
    UIFont *myAppFont = [UIFont systemFontOfSize:12.0];
    UIColor *myAppFontColor = [UIColor whiteColor];
    UIColor *myAppBackColor = RGBCOLOR(240, 43, 43);
    
    [self setCustomBadgeValue:value withFont:myAppFont andFontColor:myAppFontColor andBackgroundColor:myAppBackColor];
}



- (void)setCustomBadgeValue:(NSString *)value withFont:(UIFont *) font andFontColor:(UIColor *)color andBackgroundColor:(UIColor *) backColor
{
    NSLog(@"%@",self);

    UIView *v = self.customView;//[self valueForKey:@"selectedViewController"];
    if (!v) {
        return;
    }
    
    for(UIView *sv in v.subviews)
    {
        // REMOVE PREVIOUS IF EXIST
        if(sv.tag == CUSTOM_BADGE_TAG) { [sv removeFromSuperview]; }
        
    }
    UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 12.0, 12.0)];
    [v addSubview:l];
    [l mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(v.mas_right).offset(-7);
        make.bottom.equalTo(v.mas_top).offset(7);
        make.width.equalTo(@14);
        make.height.equalTo(@14);
    }];
    [l setFont:font];
    if ([value integerValue] > 9) {
        [l setText:@"9+"];
    }else{
        [l setText:value];
    }
    if (l.text.length > 1) {
        [l mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@22);
        }];
    }
    [l setBackgroundColor:backColor];
    [l setTextColor:color];
    [l setTextAlignment:NSTextAlignmentCenter];
    l.layer.cornerRadius = 7.0f;
    l.layer.masksToBounds = YES;
    l.tag = CUSTOM_BADGE_TAG;
    if ([l.text isEqualToString:@"0"]) {
        [self hideBadgeValue];
    }
}

- (void)hideBadgeValue
{
    UIView *v = [self valueForKey:@"view"];
    
    for(UIView *sv in v.subviews)
    {
        // REMOVE PREVIOUS IF EXIST
        if(sv.tag == CUSTOM_BADGE_TAG) { [sv removeFromSuperview]; }
        
    }
}

@end
